#!/usr/bin/env python
#coding=utf-8

import os
import sys
import shutil
import urllib2
import config

from log import log
from optparse import OptionParser

def clean_workspace(ws):
    manifests = (
        "static",
    )

    for m in manifests:
        m = os.path.join(ws, m)
        if os.path.exists(m):
            if os.path.isdir(m):
                shutil.rmtree(m)
            else:
                os.unlink(m)


def reinit_workspace(ws):
    clean_workspace(ws)

    if not os.path.exists(ws):
        os.makedirs(ws)

def copy_static_comps(ws):
    comps = (
        "ajax",
        "images",
        "jqm.iscrollview",
        "jquery",
        "swipe",
        "jqm",
        "styles",
        "iscroll",
    )

    for comp in comps:
        src = os.path.join("static", comp)
        dest = os.path.join(ws, "static", comp)

        if options.verbose: log.info("Copy %s to %s" % (src, dest));
        shutil.copytree(src, dest)


def produce_html_templates(ws, prj):
    url_prefix = "http://127.0.0.1:9000/ajax/exports/"
    tmpldir = os.path.join(config.TMPL_DIR, 'ajax', prj)
    tmpls = list()

    for tmpl in os.listdir(tmpldir):
        if os.path.isfile(os.path.join(tmpldir, tmpl)) and tmpl.endswith("html"):
            tmpls.append((tmpl.split(".")[0], tmpl))

    for tmpl in tmpls:
        log.info("Produce %s based on %s" % (tmpl[1], tmpl[0]))
        try:
            f = urllib2.urlopen(url_prefix + tmpl[0])
            open(os.path.join(ws, tmpl[1]), "w").write(f.read())
        except Exception, e:
            log.error(e)

def do_export(options):
    workspace = os.path.join(os.getcwd(), "phonegap", options.project, "www")

    if options.verbose: log.info("Reinitialize workspace %s." % workspace);
    reinit_workspace(workspace)

    if options.verbose: log.info("Copy static components to workspace.");
    copy_static_comps(workspace)

    if options.verbose: log.info("Produce html templates.");
    produce_html_templates(workspace, options.project)


def do_replace_constants(options):
    workspace = os.path.join(os.getcwd(), "phonegap", options.project, "www")

    filename = os.path.join(workspace, "static", "ajax", options.project, "constants.js")
    lines = open(filename).readlines()
    with open(filename, "w") as fh:
        for line in lines:
            if line.strip().startswith("URL_PREFIX"):
                if options.verbose: log.info("Replace URL_PREFIX with %s in workspace" % options.remote);
                line = "URL_PREFIX='%s'; // autogen variable \n" % options.remote
            elif line.strip().startswith("POLYMORHIC_MODE"):
                if options.verbose: log.info("Replace POLYMORHIC_MODE with local in workspace");
                line = "POLYMORHIC_MODE='local'; // autogen variable \n"
            fh.write(line)
        fh.close()   

if __name__ == '__main__':
    usage = "usage: %prog [options] command"
    parser = OptionParser(usage)
    parser.add_option("-p", "--output", dest="project")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
    parser.add_option("-r", "--remote", dest="remote")

    (options, cmds) = parser.parse_args()
    if len(cmds) != 1:
        parser.error("incorrect number of commands")

    if cmds[0] == 'export':
        if not options.project:
            options.project = config.AJAX_TEMPLATE
            log.warn("Project name not provided, use current project %s as default!" % options.project)

        if not options.remote:
            options.remote = "http://%s.wiaapp.cn" % options.project
            log.warn("Remote server not provided, use %s as default!" % options.remote)

        do_export(options)
        do_replace_constants(options)
    else:
        parser.error("unknown command: %s" % cmds[0])
        sys.exit(-1)

